//
//  CardDetailViewController.m
//  cherryPicker
//
//  Created by Young Soo Yun on 12. 1. 9..
//  Copyright (c) 2012 Happy. All rights reserved.
//

#import "CardDetailViewController.h"

#import "CardDetailTableViewCell.h"

@implementation CardDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    _topMenuVC = [[TopMenuViewController alloc] initWithNibName:@"TopMenuViewController" bundle:nil];
	[_topMenuVC initWithMenuType:CHERRY_MENU_CARDDETAIL];
    [_topMenuVC setVController:self];
	[_topMenuVC set_delegate:self];
    [_topMenuVC initTopMenuBtnType:TOP_LEFT_BACK right:TOP_RIGHT_MODIFY];
    
    [self.view addSubview:_topMenuVC.view];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
	G__SAFE_FREE(_topMenuVC);
    
    [super dealloc];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	return 49;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    _confirmVC = [[ConfirmViewController alloc] initWithNibName:@"ConfirmViewController" bundle:nil];
    [_confirmVC set_delegate:self];
    [_confirmVC initType:MODIFY_RECEIPT];
    [self.view addSubview:_confirmVC.view];
    
    [_confirmVC initData:[_arrData objectAtIndex:indexPath.row]];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tv numberOfRowsInSection:(NSInteger)section {
    
    return _arrData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	int row = [indexPath row];
    
    CardDetailTableViewCell * cell = (CardDetailTableViewCell *)[tv dequeueReusableCellWithIdentifier:@"CardDetailTableViewCell"];
    if(cell == nil) {
        NSArray * array = [[NSBundle mainBundle] loadNibNamed:@"CardDetailTableViewCell" owner:self options:nil];
        cell = (CardDetailTableViewCell*)[array objectAtIndex:0];
    }
    ReceiptDB* receiptDB = [_arrData objectAtIndex:row];
    
    [cell setData:receiptDB._Place
      labCategory:receiptDB._Category
          labDate:receiptDB._Date
         labPrice:[NSString stringWithFormat:@"%d", receiptDB._Price]
      labDiscount:[NSString stringWithFormat:@"%d", receiptDB._Discount]];
    
    return cell;
}

#pragma mark - TopMenuVCDelegate

- (void)topMenuVCClickRight{
    _makeCardVC = [[MakeCardViewController alloc] initWithNibName:@"MakeCardViewController" bundle:nil];
    [_makeCardVC set_delegate:self];
    [_makeCardVC initType:MODIFY_CARD];
    [self.view addSubview:_makeCardVC.view];
    [_makeCardVC setLabel:_selectedCard._CardName tag:TAG_TFCARDNAME];
    [_makeCardVC setLabel:_selectedCard._Delimiter tag:TAG_DELIMITER];
    [_makeCardVC setLabel:_selectedCard._Company tag:TAG_COMPANY];
    [_makeCardVC setLabel:[NSString stringWithFormat:@"%d 일", _selectedCard._PayDate] tag:TAG_PAYDATE];
    [_makeCardVC setLabel:[NSString stringWithFormat:@"%d 일", _selectedCard._UseDate] tag:TAG_USEDATE];
    [_makeCardVC setLabel:[NSString stringWithFormat:@"%d 만원", _selectedCard._LimitPrice/10000] tag:TAG_PRICE];
    [_makeCardVC setLabel:[NSString stringWithFormat:@"%d", _selectedCard._CardType] tag:TAG_CHECK];
}


#pragma mark - MakeCardVCDelegate

- (void)MakeCardOKClick{
    [_makeCardVC.view removeFromSuperview];
    // reload Data
    
    NSArray* arrCard = [CherryPickerDB selectFromCardList:_selectedCard._Delimiter];
    
    if (arrCard !=nil && arrCard.count > 0) {
        _selectedCard = [arrCard objectAtIndex:0];
    }

    // update info
    _labCardName.text = [NSString stringWithFormat:@"%@ (%@)", _selectedCard._CardName, _selectedCard._Company];

    // update New CardName in Receipt
    [CherryPickerDB updateToReceipt:_selectedCard._Delimiter newCardName:_selectedCard._CardName];
    _arrData = [CherryPickerDB selectFromReceipt:_selectedCard._Delimiter];
    [_tvList reloadData];

}

- (void)MakeCardCancelClick{
    [_makeCardVC.view removeFromSuperview];
}

- (void)MakeCardPickerView:(NSString*)labText
                       tag:(NSInteger)tag{
    SimplePickerViewController * controller = [[SimplePickerViewController alloc] initWithNibName:@"SimplePickerViewController" bundle:nil];
    controller.delegate = self;
    
    _simplePickerTag = tag;
    
    switch (tag) {
        case TAG_DELIMITER:
            break;
        case TAG_COMPANY:
            controller.dataArray = [[NSArray alloc] initWithObjects:@"현대카드",
                                    @"신한카드",
                                    @"KB국민카드",
                                    @"롯데카드",
                                    @"외환카드",
                                    @"시티은행카드(구 한미카드)",
                                    @"우리카드(평화)",
                                    @"비씨카드",
                                    @"삼성카드",
                                    @"하나SK카드",
                                    @"광주은행카드",
                                    @"수협은행카드",
                                    @"전북은행카드",
                                    @"제주은행카드",
                                    @"강원은행카드",
                                    @"저축은행체크카드",
                                    @"산업은행카드",
                                    @"농협NH카드",
                                    nil];
            break;
        case TAG_PAYDATE:
        case TAG_USEDATE:{
            NSMutableArray* arrDate = [[NSMutableArray alloc] init];
            for (int i = 1; i < 31; i++) {
                [arrDate addObject:[NSString stringWithFormat:@"%d 일", i]];
            }
            controller.dataArray = arrDate;
            
            break;
        }
        case TAG_PRICE:{
            NSMutableArray* arrMoney = [[NSMutableArray alloc] init];
            for (int i = 1; i < 11; i++) {
                [arrMoney addObject:[NSString stringWithFormat:@"%d 만원", i*10]];
            }
            controller.dataArray = arrMoney;
            break;
        }
    }
    
    if (tag != TAG_DELIMITER) {
        for (int i = 0; i < controller.dataArray.count; i++) {
            if ([labText isEqualToString:[controller.dataArray objectAtIndex:i]]) {
                [controller setPickerIndex:i];
                break;
            }
        }
        
        [self.view addSubview:controller.view];
    }
}

- (void)MakeCardDelClick{
    [_makeCardVC.view removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - ConfirmVCDelegate

- (void)ConfirmOKClick{
    
    _arrData = [CherryPickerDB selectFromReceipt:_selectedCard._Delimiter];
    [_tvList reloadData];
    
    [_confirmVC.view removeFromSuperview];
}

- (void)ConfirmCancelClick{
    [_confirmVC.view removeFromSuperview];
}

- (void)ConfirmPickerView:(NSInteger)tag labText:(NSString *)labText{
    switch (tag) {
        case TAG_CARDNAME:{
            break;
        }
        case TAG_DATE:{
            DatePickerViewController * controller = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:nil];
            controller.delegate = self;
            [controller initDatePosition:labText];
            _simplePickerTag = tag;
            
            [self.view addSubview:controller.view];
            
            break;
        }
        case TAG_CATEGORY:{
            SimplePickerViewController * controller = [[SimplePickerViewController alloc] initWithNibName:@"SimplePickerViewController" bundle:nil];
            controller.delegate = self;
            
            _simplePickerTag = tag;
            
            controller.dataArray = [[NSArray alloc] initWithObjects:@"식비",
                                    @"주거",
                                    @"통신",
                                    @"생활용품",
                                    @"의복",
                                    @"건강",
                                    @"문화"
                                    @"교통",
                                    @"교육",
                                    @"육아",
                                    nil];
            
            for (int i = 0; i < controller.dataArray.count; i++) {
                if ([labText isEqualToString:[controller.dataArray objectAtIndex:i]]) {
                    [controller setPickerIndex:i];
                    break;
                }
            }
            
            [self.view addSubview:controller.view];
            
            break;
        }
        case TAG_PLACE:{
            break;
            
        }
    }
}

- (void)ConfimKeyBoard:(BOOL)isON{
    CGRect moveFrame = (isON)?CGRectMake(0.0f, - 100.0f, 320.0f, 460.0f):
    CGRectMake(0.0f, 0.0f, 320.0f, 460.0f);
    
    CGFloat animationDuration = 0.3;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    _confirmVC.view.frame = moveFrame;
    [UIView commitAnimations];
}

- (void)ConfimDelClick{
    _arrData = [CherryPickerDB selectFromReceipt:_selectedCard._Delimiter];
    [_tvList reloadData];
    
    [_confirmVC.view removeFromSuperview];
}

#pragma mark - SimplePickerViewControllerDelegate

- (void)simplePickerViewControllerDidSelected:(SimplePickerViewController *)controller selectedIndex:(int)index{
    
    if (_simplePickerTag < 6) {
        [_makeCardVC setLabel:[controller.dataArray objectAtIndex:index] tag:_simplePickerTag];
    }else{
        [_confirmVC setLabel:[controller.dataArray objectAtIndex:index] tag:_simplePickerTag];
    }
    
    [controller.view removeFromSuperview];
}

- (void)simplePickerViewControllerDidCancelled:(SimplePickerViewController *)controller{
    [controller.view removeFromSuperview];
}

#pragma mark - DatePickerViewControllerDelegate

- (void)datePickerViewControllerDidSelected:(DatePickerViewController *)controller dateStr:(NSString*)dateStr{
    [_confirmVC setDate:dateStr];
    
    [controller.view removeFromSuperview];
}

- (void)datePickerViewControllerDidCancelled:(DatePickerViewController *)controller{
    [controller.view removeFromSuperview];
}


#pragma mark -

- (void)initViewData:(CardListDB*)cardDB{
    _selectedCard = [cardDB retain];
    
    _labCardName.text = [NSString stringWithFormat:@"%@ (%@)",cardDB._CardName, cardDB._Company];
    
    _arrData = [CherryPickerDB selectFromReceipt:cardDB._Delimiter];
    
    [_tvList reloadData];
}

@end
